/*
消息格式适配器
连接waterbear和ebbflow的消息格式
*/

package communication

import (
	"ebbflow/src/message"
	"encoding/json"
	"fmt"
	"time"
)

// MessageAdapter 消息格式适配器
type MessageAdapter struct {
	// 可以添加配置参数
}

// NewMessageAdapter 创建消息适配器
func NewMessageAdapter() *MessageAdapter {
	return &MessageAdapter{}
}

// ConvertToWaterbearMessage 将ebbflow消息转换为waterbear格式
func (ma *MessageAdapter) ConvertToWaterbearMessage(ebbMsg message.ReplicaMessage) ([]byte, error) {
	// 创建waterbear消息格式
	waterbearMsg := map[string]interface{}{
		"type":      ebbMsg.Mtype,
		"instance":  ebbMsg.Instance,
		"source":    ebbMsg.Source,
		"timestamp": ebbMsg.TS,
		"payload":   ebbMsg.Payload,
		"epoch":     ebbMsg.Epoch,
	}
	
	// 序列化为JSON
	data, err := json.Marshal(waterbearMsg)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal waterbear message: %v", err)
	}
	
	return data, nil
}

// ConvertFromWaterbearMessage 将waterbear消息转换为ebbflow格式
func (ma *MessageAdapter) ConvertFromWaterbearMessage(data []byte) (*message.ReplicaMessage, error) {
	// 解析waterbear消息
	var waterbearMsg map[string]interface{}
	if err := json.Unmarshal(data, &waterbearMsg); err != nil {
		return nil, fmt.Errorf("failed to unmarshal waterbear message: %v", err)
	}
	
	// 转换为ebbflow消息格式
	ebbMsg := &message.ReplicaMessage{
		Mtype: message.TypeOfMessage(int(waterbearMsg["type"].(float64))),
		Instance: int(waterbearMsg["instance"].(float64)),
		Source:  int64(waterbearMsg["source"].(float64)),
		TS:      int64(waterbearMsg["timestamp"].(float64)),
		Payload: []byte(waterbearMsg["payload"].(string)),
		Epoch: int(waterbearMsg["epoch"].(float64)),
	}
	
	return ebbMsg, nil
}

// CreateConsensusMessage 创建共识消息
func (ma *MessageAdapter) CreateConsensusMessage(msgType int, instance int64, source int64, payload []byte, epoch int64) *message.ReplicaMessage {
	return &message.ReplicaMessage{
		Mtype: message.TypeOfMessage(msgType),
		Instance: int(instance),
		Source:   source,
		TS:       time.Now().UnixNano(),
		Payload:  payload,
		Epoch: int(epoch),
	}
}

// CreateNetworkMessage 创建网络消息
func (ma *MessageAdapter) CreateNetworkMessage(msgType int, instance int64, source int64, payload []byte) *message.ReplicaMessage {
	return &message.ReplicaMessage{
		Mtype: message.TypeOfMessage(msgType),
		Instance: int(instance),
		Source:   source,
		TS:       time.Now().UnixNano(),
		Payload:  payload,
		Epoch:    1, // 默认epoch
	}
}
